<?php
namespace control;

// 人员结构报表
class personnelStructureClass extends adIndexClass
{
    private const page = 'personnelStructure';
    private array $list = ['dep_distribute' => '部门人数分布', 'age_distribute' => '年龄分布', 'education_distribute' => '学历分布', 'sex_distribute' => '性别分布', 'working_years_distribute' => '工龄分布'];

    /*返回网页*/
    public function home()
    {
        $root = root;
        // 搜索文本框
        $searchTxt =
            "<form name='mainForm'>" .
            selectMultiple(["name" => "departmentId", 'table' => " department", 'class' => " text width200", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '部门']).
            "<input class='searchSub' type='button' onclick='cardSearch()' value='查询'></form>";

        //$record = query('user_setting',"stid = '".self::$stid."' and type = '人员结构'");
        $setting = ["dep_distribute", "age_distribute", "education_distribute", "sex_distribute", "working_years_distribute"];
        $dep_distribute = in_array('dep_distribute', $setting) ? 'display:block;' : 'display:none;';
        $age_distribute = in_array('age_distribute', $setting) ? 'display:block;' : 'display:none;';
        $education_distribute = in_array('education_distribute', $setting) ? 'display:block;' : 'display:none;';
        $sex_distribute = in_array('sex_distribute', $setting) ? 'display:block;' : 'display:none;';
        $working_years_distribute = in_array('working_years_distribute', $setting) ? 'display:block;' : 'display:none;';

        $html = <<<EOT
        <style>
            .title-card-li-content{
              text-align: center;padding-top: 50px
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
            .spread-box{
                float: left;
                margin: 5px 0 -5px 0;
                width: 98.5%;
            }
            .time_switching{
                display: inline-block;
                width: 80px;
                height: 26px;
                line-height: 26px;
                background-color: #e6e6e6;
                text-align: center;
                margin-right: 15px;
                cursor: pointer;
            }
            .text-data{
                margin-right: 15px;
            }
            .quarter {
                width: 19%;
            }
        </style>
        <!--<div class="chart_setting"><img onclick="layer('salesReportForm','setting',{})" src="{$root}img/control/menu_two.svg" alt=""></div>-->
        <div class="home-warp">
            <div class="spread-box">
                <div class="data-widget search">$searchTxt</div>
            </div>
            <div class="left-box">
                <div class="half left data-widget" style="width: 97.5%;{$dep_distribute}">
                    <p><span class="title-card">部门人数分布</span></p>
                   <div class="data-box-show" id="depDistributeHtml"></div>
                </div>
                <div class="half left data-widget" style="{$age_distribute}">
                    <p><span class=\"title-card\">年龄分布</span></p>
                    <div class="data-box-show" id="ageDistributeHtml"></div>
                </div>
                <div class="half left data-widget" style="{$education_distribute}">
                    <p><span class=\"title-card\">学历分布</span></p>
                    <div class="data-box-show" id="educationDistributeHtml"></div>
                </div>
            </div>
            <div class="right-box">
              <div class="data-widget" style="{$sex_distribute}">
                   <p><span class="title-card">性别分布</span></p>
                   <div class="data-box-show" id="sexDistributeHtml"></div>
                </div>
                <div class="data-widget" style="{$working_years_distribute}">
                   <p><span class="title-card">工龄分布</span></p>
                   <div class="data-box-show" id="workingYearsDistributeHtml"></div>
                </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function search_line(form,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
     //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, serialize, function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}

/**
* 看板搜索
*/
function cardSearch(){
    ['depDistribute', 'ageDistribute', 'educationDistribute', 'sexDistribute', 'workingYearsDistribute'].forEach((fun)=>{
                    search_line('mainForm','personnelStructure', fun)
    });
}

$(function() {
    ['depDistribute', 'ageDistribute', 'educationDistribute', 'sexDistribute', 'workingYearsDistribute'].forEach((fun)=>{
                    search_line('mainForm','personnelStructure', fun)
    });
})


</script>
EOT;
        $style = '<style>#body{background-color:#f2f2f2;padding:0 10px}.right-box-ul{
            height: 500px;
            max-height: none;
         }
         .right-box-title{
            display: flex;
         }
         .right-text{
            height: auto;
         }
         .right-box-title li{
            float: left;margin: 5px 10px;min-width: 70px;text-align: center;
         }
         .data-widget-select{
            margin-right: 10px;
         }
         .data-widget-select .fs-label{
             height: 15px;line-height: 15px;
         }
         .data-widget-select .fs-label-wrap{
             border-radius: 4px;
         }
         .aim-rank li{
            margin: 5px 0;
         }
         .aim-rank .right-box-title li:nth-child(1){min-width: 40px}
         .aim-rank .right-box-title li:nth-child(2){min-width: 50px}
         .aim-rank .right-box-title li:nth-child(3){min-width: 100px}
         .aim-rank .right-box-title li:nth-child(4){min-width: 100px}
</style>';
        return head("ad") . $style . $this->adheader(["主页"]) . $html . warn() . $this->adfooter();
    }

    /**
     * 显示设置
     * @return bool|string
     */
    public function setting()
    {
        $list = $this->list;
        $li = '';
        $index = 0;
        $setting = query('user_setting', "type='人员结构' and stid = '" . self::$stid . "'");
        $setText = (array)json_decode($setting['value'], true);
        foreach ($list as $id => $name) {
            $index++;
            $checked = '';
            if (in_array($id, $setText)) {
                $checked = 'checked';
            }
            $li .= <<<eof
 <li><div class="li-content"><span class="left">{$name}</span><div class="switch">
                  <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
                  <label for="cmn-toggle-{$index}"></label>
            </div></div></li>
eof;
        }
        //生成表单
        $html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
   
</div>
<div style="width: 100%;text-align: center"><button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesReportForm&fun=settingEdit')">保存</button></div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

        //返回弹出层
        return $this->layer(array("title" => '设置图表展示', "height" => 550, "width" => 400, "html" => $html));
    }

    /**
     * 图标展示设置
     * @return bool|string
     */
    public function settingEdit(): bool|string
    {
        $setting = $this->post('setting') ?: [];
        $record = query('user_setting', "type='人员结构' and stid = '" . self::$stid . "'");
        if (!empty($record['id'])) {
            $json['warn'] = static::update(array(
                'table' => 'user_setting',
                'field' => [
                    'value' => json_encode($setting, 320)
                ],
                'where' => "id = '$record[id]'"
            ));
        } else {
            $json['warn'] = static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid' => self::$stid,
                    'type' => '人员结构',
                    'value' => json_encode($setting, 320)
                ],
            ));
        }
        if (in_array($json['warn'], ['新增成功', '更新成功'])) {
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 部门人数分布 - 返回数据
     */
    public function depDistribute(): bool|string
    {
        $department = $this->post('departmentId');
        //未选部门时列示所有一级部门
        if (empty($department)) {
            $arr = find([
                'table' => "department",
                'field' => "id,name",
                'where' => " pid = '0' ",
            ]);
        } else {
            $arr = find([
                'table' => "department",
                'field' => "id,name",
                'where' => " pid = '$department' ",
            ]);
            //没有下级部门的列示本部门
            if (static::isNull($arr['array'])) {
                $query          = query("department", " id = '$department' ", 'id,name');
                $arr['array'][] = $query;
            }
        }
        $res = [];
        foreach ((array)$arr['array'] as $array) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$array[id]' "]);
            $departments = array_merge([$array['id']], explode(',', trim($departments)));
            $res[]       = [
                'department' => $array['name'],
                'people'   =>  static::total(array('table' => 'staff', 'where' => "jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) and state !='离职'")),
                'staffing'    => find([
                        'table'  => "job",
                        'field'  => "IFNULL(sum(people),0) as num",
                        'single' => " departmentId in ('" . implode("','", $departments) . "') ",
                    ])['num'] ?? 0,
            ];
        }
        $data         = [
            "name"   => array_column($res, 'department'),
            "series" => [
                [
                    'name' => '现编人数',
                    'data' => array_column($res, 'people'),
                ],
                [
                    'name' => '定编人数',
                    'data' => array_column($res, 'staffing'),
                ],
            ],
        ];
        $json['html'] = $this->barCharts($data);
        return json_encode($json, 320);
    }

    /**
     * 年龄分布 数据
     *
     * @return string
     */
    public function ageDistribute(): string
    {
        $departmentId = $this->post('departmentId');
        $res     = [];
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $typeArr = ['20岁以下','20-30岁','30-40岁','40-50岁','50岁及以上'];
        foreach ($typeArr as $k=>$type) {
            $where = "";
            switch ($k){
                case 0:
                    $where = " and DATEDIFF(CURDATE(), birthDay)/365.2422 < 20 ";
                    break;
                case 1:
                    $where = " and DATEDIFF(CURDATE(), birthDay)/365.2422 >=20 0 and DATEDIFF(CURDATE(), birthDay)/365.2422 < 30 ";
                    break;
                case 2:
                    $where = " and DATEDIFF(CURDATE(), birthDay)/365.2422 >= 30 and DATEDIFF(CURDATE(), birthDay)/365.2422 < 40 ";
                    break;
                case 3:
                    $where = " and DATEDIFF(CURDATE(), birthDay)/365.2422 >= 40 and DATEDIFF(CURDATE(), birthDay)/365.2422 < 50 ";
                    break;
                case 4:
                    $where = " and DATEDIFF(CURDATE(), birthDay)/365.2422 >= 50 ";
                    break;
            }
            $res[] = [
                'text'     => $type,
                'num' => find([
                        'table'  => "staff",
                        'field'  => "IFNULL(count(stid),0) as num",
                        'single' => " state !='离职' and talentId in (select id from talent_pool where 1=1 {$where}) " . $and,
                    ])['num'] ?? 0,
            ];
        }

        $data         = [
            "name"   => array_column($res, 'text'),
            "series" => [
                [
                    'name' => '人数',
                    'data' => array_column($res, 'num'),
                ],
            ],
        ];
        $json['html'] = $this->barCharts($data);
        return json_encode($json, 320);
    }

    /**
     * 学历分布 数据
     *
     * @return string
     */
    public function educationDistribute(): string
    {
        $departmentId = $this->post('departmentId');
        $res     = [];
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $typeArr = explode('，', para('education'));
        foreach ($typeArr as $k=>$type) {
            $where = " and education = '$type' ";
            $res[] = [
                'text'     => $type,
                'num' => find([
                        'table'  => "staff",
                        'field'  => "IFNULL(count(stid),0) as num",
                        'single' => " state !='离职' and talentId in (select id from talent_pool where 1=1 {$where}) " . $and,
                    ])['num'] ?? 0,
            ];
        }

        $data         = [
            "name"   => array_column($res, 'text'),
            "series" => [
                [
                    'name' => '人数',
                    'data' => array_column($res, 'num'),
                ],
            ],
        ];
        $json['html'] = $this->barCharts($data);
        return json_encode($json, 320);
    }

    /**
     * 性别分布 - 返回数据
     */
    public function sexDistribute(): bool|string
    {
        $inventoryReportForm = new inventoryReportFormClass();
        $departmentId = $this->post('departmentId');
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $data         = [
            "text" => '',
            "subtext" => '',
            "series" => [
                ['name' => "男", 'data' => find([
                        'table'  => "staff",
                        'field'  => "IFNULL(count(stid),0) as num",
                        'single' => " state !='离职' and talentId in (select id from talent_pool where 1=1 and sex = '男') " . $and,
                    ])['num'] ?? 0],
                ['name' => "女", 'data' => find([
                        'table'  => "staff",
                        'field'  => "IFNULL(count(stid),0) as num",
                        'single' => " state !='离职' and talentId in (select id from talent_pool where 1=1 and sex = '女') " . $and,
                    ])['num'] ?? 0]
            ],
        ];
        $json['html'] = "<div style='height: 100%'>".$inventoryReportForm->pie($data)."</div>";
        return json_encode($json, 320);
    }
    /**
     * 工龄分布 - 返回数据
     */
    public function workingYearsDistribute(): bool|string
    {
        $inventoryReportForm = new inventoryReportFormClass();
        $departmentId = $this->post('departmentId');
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $workingYear = ['0-1年','1-3年','3-5年','5-10年','10年以上'];
        $series = [];
        foreach ($workingYear as $k=>$val) {
            $where = "";
            switch ($k){
                case 0:
                    $where = " and DATEDIFF(CURDATE(), entryDate)/365.2422 > 0 and DATEDIFF(CURDATE(), entryDate)/365.2422 <= 1 ";
                    break;
                case 1:
                    $where = " and DATEDIFF(CURDATE(), entryDate)/365.2422 > 1 and DATEDIFF(CURDATE(), entryDate)/365.2422 <= 3 ";
                    break;
                case 2:
                    $where = " and DATEDIFF(CURDATE(), entryDate)/365.2422 > 3 and DATEDIFF(CURDATE(), entryDate)/365.2422 <= 5 ";
                    break;
                case 3:
                    $where = " and DATEDIFF(CURDATE(), entryDate)/365.2422 > 5 and DATEDIFF(CURDATE(), entryDate)/365.2422 <= 10 ";
                    break;
                case 4:
                    $where = " and DATEDIFF(CURDATE(), entryDate)/365.2422 > 10 ";
                    break;
            }
            $quitNum = find([
                    'table'  => "staff",
                    'field'  => "IFNULL(count(stid),0) as num",
                    'single' => " state !='离职' and talentId in (select talentId from staff_entry_record where 1=1 and state = '已通过' {$where}) " . $and,
                ])['num'] ?? 0;
            $series[] = ['name' => $val, 'data' => $quitNum];
        }
        $data         = [
            "text" => '',
            "subtext" => '',
            "series" => $series,
        ];
        $json['html'] = "<div style='height: 100%'>".$inventoryReportForm->pie($data)."</div>";
        return json_encode($json, 320);
    }
}
